<template>
  <div class="consultation">
    <div class="consultation-block">
      <h3 style="margin-bottom: 20px;">考试列表</h3>
      <div class="flex-center">
        <el-input v-model="key" size="mini" style="width: 120px;" placeholder="关键字/词查询"></el-input>
        <el-button class="ml0" size="mini" type="primary" @click="getExams(true)"
          >查询</el-button
        >
      </div>
      <div class="table">
        <el-table size="mini" :data="tableDataExam" style="width: 100%">
          <el-table-column label="序号" type="index"> </el-table-column>
          <el-table-column prop="paper.name" label="试卷名称"> </el-table-column>
          <el-table-column prop="user.nickname" label="考生"> </el-table-column>
          <el-table-column prop="stuTime" label="考试时间"> </el-table-column>
          <el-table-column prop="score" label="分数"> </el-table-column>
          <el-table-column label="操作" width="250">
            <template slot-scope="scope">
              <el-button
                type="success"
                size="mini"
                @click="view(scope.row)"
                >查看试卷</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="pagination">
        <el-pagination
          background
          layout="prev, pager, next"
          :current-page.sync="currentPage"
          @current-change="getExams"
          :page-size="pageSize"
          :total="total"
        >
        </el-pagination>
      </div>
    </div></el-tab-pane>
    <el-dialog
      :title="title"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="dialogVisible"
      width="60%"
      :before-close="handleClose"
    >
      <div class="paper-content">
        <div v-if="questions['填空'] && questions['填空'].length">
          <h4>填空</h4>
          <div v-for="(test, i) in questions['填空']" :key="i">
            <div class="name">
              <div>{{ i + 1 }}.</div>
              <div style="width: 80%;" v-html="test.name"></div>
              <div class="score">分数：{{ test.score }}</div>
            </div>
            <div v-for="(s, index) in test.answer" :key="index">
              <el-input
                style="width: 100%;margin-top: 10px;"
                disabled
                v-model="s.answer"
                >
              </el-input>
              <div class="judge">
                <div v-if="s.answer == test.selections[index].text">回答正确</div>
                <div v-if="s.answer !== test.selections[index].text">正确答案：{{ test.selections[index].text }}</div>
              </div>
            </div>
          </div>
        </div>
        <div v-if="questions['单选'] && questions['单选'].length">
          <h4>单选</h4>
          <div v-for="(test, i) in questions['单选']">
            <div class="name">
              <div>{{ i + 1 }}.</div>
              <div v-html="test.name"></div>
              <div class="score">分数：{{ test.score }}</div>
            </div>
            <el-radio-group :disabled="title != '开始考试'" v-model="test.answer">
              <el-radio
                style="width: 100%;margin-top: 10px;"
                v-for="(s, index) in test.selections"
                :label="index"
                >
                <div class="flex-center">
                  <div>{{ handleABC(index) }}</div>
                  <div v-html="s.text"></div>
                </div>
              </el-radio>
            </el-radio-group>
            <div class="judge">
              <div v-if="test.selections[test.answer].checked">回答正确</div>
              <div v-if="!test.selections[test.answer].checked">正确答案：{{ test.duicuoTxet }}</div>
            </div>
          </div>
        </div>
        <div v-if="questions['多选'] && questions['多选'].length">
          <h4>多选</h4>
          <div v-for="(test, i) in questions['多选']">
            <div class="name">
              <div>{{ i + 1 }}.</div>
              <div v-html="test.name"></div>
              <div class="score">分数：{{ test.score }}</div>
            </div>
            <el-checkbox-group :disabled="title != '开始考试'" v-model="test.answer">
              <el-checkbox
                style="width: 100%;margin-top: 10px;"
                v-for="(s, index) in test.selections"
                :label="index"
                >
                
                <div class="flex-center">
                  <div>{{ handleABC(index) }}</div>
                  <div v-html="s.text"></div>
                </div>
                </el-checkbox
              >
            </el-checkbox-group>
            <div class="judge">
              <div v-if="test.duicuo">回答正确</div>
              <div v-if="!test.duicuo">正确答案：{{ test.duicuoTxet }}</div>
            </div>
          </div>
        </div>
        <div v-if="questions['判断'] && questions['判断'].length">
          <h4>判断</h4>
          <div v-for="(test, i) in questions['判断']">
            <div class="name">
              <div>{{ i + 1 }}.</div>
              <div v-html="test.name"></div>
              <div class="score">分数：{{ test.score }}</div>
            </div>
            <el-radio-group :disabled="title != '开始考试'" v-model="test.answer">
              <el-radio
                style="width: 100%;margin-top: 10px;"
                v-for="(s, index) in test.selections"
                :label="index"
                >
                
                <div class="flex-center">
                  <div>{{ handleABC(index) }}</div>
                  <div v-html="s.text"></div>
                </div>
                </el-radio
              >
            </el-radio-group>
            <div class="judge">
              <div v-if="test.selections[test.answer].checked">回答正确</div>
              <div v-if="!test.selections[test.answer].checked">正确答案：{{ test.duicuoTxet }}</div>
            </div>
          </div>
        </div>
        <div v-if="questions['主观题'] && questions['主观题'].length">
          <h4>主观题</h4>
          <div v-for="(test, i) in questions['主观题']">
            <div class="name">
              <div>{{ i + 1 }}.</div>
              <div v-html="test.name"></div>
              <div class="score">分数：{{ test.score }}</div>
            </div>
            <div class="mt10">
              <h4>考生答案</h4>
              <div v-html="test.answer"></div>
            </div>
            <div class="flex-center mt10">
              <div>打分</div>
              <el-input-number :disabled="currentRow.score" v-model="test.scoreGet" :min="0" :max="Number(test.score)" label="请打分"></el-input-number>
            </div>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" 
          >关 闭</el-button
        >
        <el-button v-if="!currentRow.score" type="primary" @click="commit" :loading="btnLoading"
          >打 分</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import moment from 'moment'
import { getExam, updateExam, addWrong } from "../service.js";
import { numberToLetter } from '../tools/index'
export default {
  name: "home",
  mounted() {
    this.getExams();
  },
  data() {
    return {
      tableDataPaper: [],
      tableDataExam: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      questions: {},
      dialogVisible: false,
      title: '',
      currentRow: '',
      key: '',
      btnLoading: false
    };
  },
  methods: {
    getExams(init = false) {
      if (init) {
        this.currentPage = 1;
      }
      let params = {
        pageSize: this.pageSize,
        page: this.currentPage,
      };
      if (this.key) {
        params.key = this.key
      }
      getExam(params).then((res) => {
        this.tableDataExam = res.code === 200 ? res.data.data : [];
        this.total = res.data.total;
      });
    },
    handleClose() {
      this.dialogVisible = false;
    },
    view(row) {
      this.currentRow = row
      this.questions = JSON.parse(row.paperInfo)
      this.title = '查看试卷'
      this.btnLoading = false;
      this.dialogVisible = true;
      for (let key in this.questions) {
        
        for (let each of this.questions[key]) {
          if (key == '多选') {
            each.duicuo = true
            for (let a of each.answer) {
              if (!each.selections[a].checked) {
                each.duicuo = false;
                break
              }
            }
            if (each.duicuo && each.answer.length !== each.selections.filter(v => v.checked).length) {
              each.duicuo = false;
            }
          }
          let checkedIndices = each.selections.reduce((indices, obj, index) => {  
            if (obj.checked) {  
              indices.push(index);  
            }  
            return indices;  
          }, []);
          checkedIndices = checkedIndices.map(v => {
            return numberToLetter(v)
          })
          each.duicuoTxet = checkedIndices.join('、')
        }
        
      }
      console.log(this.questions)
    },
    commit() {
      // this.btnLoading = true;
      let wrongList = []
      // 修改
      // 错题进库
      let flag = null;
      if (this.questions['主观题']) {
        for (let val of this.questions['主观题']) {
          if (!val.scoreGet) {
            flag = val
          }
        }
      }
      if (flag) {
        this.$message.error(`${flag.type}: ${flag.name} 未打分`)
        this.btnLoading = false;
        return
      }
      // 计算总分
      let score = 0;
      for (let key in this.questions) {
        if (key == '主观题') {
          for (let each of this.questions[key]) {
            score += each.scoreGet
            if (each.scoreGet < Number(each.score)) {
              wrongList.push({
                type: '主观题',
                stuId: this.currentRow.stuId,
                questionId: each.id,
                detail: JSON.stringify(each)
              })
            }
          }
        } else if (key == '多选') {
          for (let each of this.questions[key]) {
            let duicuo = true
            for (let a of each.answer) {
              if (!each.selections[a].checked) {
                duicuo = false;
                wrongList.push({
                  type: '多选',
                  stuId: this.currentRow.stuId,
                  questionId: each.id,
                  detail: JSON.stringify(each)
                })
                break
              }
            }
            if (duicuo && each.answer.length !== each.selections.filter(v => v.checked).length) {
              wrongList.push({
                type: '多选',
                stuId: this.currentRow.stuId,
                questionId: each.id,
                detail: JSON.stringify(each)
              })
            }
            if (duicuo) {
              score +=  each.answer.length == each.selections.filter(v => v.checked).length ? Number(each.score) :  Number(each.score) * (each.answer.length / each.selections.filter(v => v.checked).length)
            }
          }
        } else if (key == '填空') {
          for (let each of this.questions[key]) {
            console.log(each)
            let wrong = false;
            for (let i = 0;i < each.answer.length;i++) {
              if (each.answer[i].answer == each.selections[i].text) {
                score += Number(each.score) / each.selections.length
              } else {
                wrong = true;
              }
              wrongList.push({
                type: key,
                stuId: this.currentRow.stuId,
                questionId: each.id,
                detail: JSON.stringify(each)
              })
            }
          }
        } else {
          for (let each of this.questions[key]) {
            let duicuo = true
            if (!each.selections[each.answer].checked) {
              duicuo = false;
              wrongList.push({
                type: key,
                stuId: this.currentRow.stuId,
                questionId: each.id,
                detail: JSON.stringify(each)
              })
              break
            }
            score +=  duicuo ? Number(each.score) :  Number(each.score) / 2
          }
        }
      }
      updateExam(this.currentRow.id, {
        teaId: JSON.parse(localStorage.getItem('userInfo')).id,
        teaTime: moment().format('YYYY-MM-DD HH:mm:ss'),
        score: Math.round(score),
        paperInfo: JSON.stringify(this.questions)
      }).then(res => {
        if (res.code == 200) {
          // 错题入库
          addWrong({
            list: wrongList
          }).then(w => {
            if (w.code == 200) {
              this.$message.success('操作成功')
              this.dialogVisible = false;
              this.getExams()
            }
          })
        }
      })
    },
    handleABC(v) {
      return numberToLetter(v)
    }
  },
};
</script>

<style lang="scss" scoped>
h2 {
  text-align: center;
  margin-top: 20px;
  margin-bottom: 20px;
}
h4 {
  margin-bottom: 20px;
  font-size: 20px;
  color: #333;
}

.paper-content {
  max-height: 60vh;
  overflow: hidden;
  overflow-y: scroll;
  & > div {
    margin-bottom: 20px;
  }
  & > div>div {
    margin-bottom: 10px;
  }
  .name {
    font-weight: bold;
    color: #333;
    display: flex;
    gap: 10px;
  }
}
.mb10 {
  margin-bottom: 10px;
}
.score {
  font-weight: bold;
  color: #666;
  margin-left: 20px;
}
.judge {
  margin-top: 10px;
  color: red;
  font-weight: bold;
}
.el-radio {
  display: flex;
}
.mt10 {
  margin-top: 10px;
}
</style>
